import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'
import { GetStorePlaceList, GetAllStorePlaceList } from '@/utils/api/BasicManagement/locations'
import { GetAllStation } from '@/utils/api/dispatch/station'
import { dialogStoreHook } from "@/store/modules/dialog";
const dialogStatus = dialogStoreHook();

import {
    addInspectionroute,
    upDataInspectionroute,
    upDataStatusInspectionroute,
    deleteInspectionroute,
    getInspectionroute,
    inspectionrouteList
} from '@/utils/api/dispatch/insoection'

const { tagStyle } = usePublicHooks();

// 路线类型
function formatType(status) {
    const stateMap = {
        0: '循环触发',
        1: '定时触发',
        2: '指定时间触发',
    }
    return stateMap[status]
}


export function useDept() {
    const form = reactive({
        name: "",
        status: null,
        type: null,
        pageNumber: 0,
        pageSize: 10,
        sortName: "",
        sortType: 0
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });

    const columns: TableColumnList = [
        {
            label: "名称",
            prop: "name",
            width: 120,
            align: "left",
        },
        {
            label: "执行AGV",
            prop: "agvNameList",
            width: 160,
            align: "left",
        },
        {
            label: "类型",
            prop: "type",
            width: 160,
            align: "left",
            cellRenderer: ({ row, props }) => { return formatType(row.type); }
        },
        {
            label: "间隔时间",
            prop: "intervaltime",
            width: 160,
            align: "left",
            cellRenderer: ({ row, props }) => {
                return row.intervaltime === 0 ? "无" : row.intervaltime + "分钟"
            }
        },
        {
            label: "触发时间",
            prop: "triggertime",
            width: 160,
            align: "left",
            cellRenderer: ({ row, props }) => {
                return row.triggertime === '' ? "无" : row.triggertime
            }
        },
        {
            label: "状态",
            prop: "status",
            width: 100,
            align: "left",
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.status)}>
                    {row.status === 1 ? "启用" : "禁用"}
                </el-tag>
            )
        },
        {
            label: "备注",
            prop: "note",
            minWidth: 200,
            align: "left"
        },
        {
            label: "操作",
            fixed: "right",
            width: 200,
            slot: "operation"
        }
    ]

    // 定义一个异步函数 onSearch 用于处理搜索操作
    async function onSearch() {
        // 将 loading 状态设置为 true，表示正在加载数据
        loading.value = true;
        const { Content }: any = await inspectionrouteList(form);
        let newData = Content.Results;
        // const res: any = await getInspectionroute(1)
        // dataList.value = [res.Content];
        dataList.value = newData;
        // 更新分页信息
        // 将 Content.TotalCount 赋值给 pagination.total，表示总的数据条数
        pagination.total = Content.TotalCount;
        // 将 Content.PageSize 赋值给 pagination.pageSize，表示每页显示的数据条数
        pagination.pageSize = Content.PageSize;
        // 将 Content.PageNumber + 1 赋值给 pagination.currentPage，表示当前页码
        // PageNumber 从 0 开始计数，因此需要加 1
        pagination.currentPage = Content.PageNumber + 1;

        // 使用 setTimeout 函数延迟 500 毫秒后执行
        // 将 loading 状态设置为 false，表示加载完成
        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    async function openDialog(title = "新增", row?: FormItemProps) {
        dialogStatus.getTitle(title)
        if (title === '编辑') {
            const { Content }: any = await getInspectionroute(row.id)
            row = Content
        }
        addDialog({
            title: `${title}路线`,
            // 设置组件的属性
            props: {
                // 表单内联属性
                formInline: {
                    name: row?.name ?? "",
                    // 字符串转为数组
                    agvids: row?.agvids?.split(',').map(v => { return Number(v) }) ?? [],
                    type: row?.type ?? "",
                    intervaltime: row?.intervaltime ?? "",
                    triggertime: row?.triggertime ?? "",
                    status: row?.status ?? 1,
                    note: row?.note ?? "",
                    stationList: row?.stationList ?? [{}],
                    agvNameList: row?.agvNameList ?? [],
                },
            },
            // 设置对话框的宽度为35%
            width: "45%",
            // 设置对话框是否可拖动
            draggable: true,
            // 设置对话框是否显示全屏图标
            fullscreenIcon: true,
            // 设置点击模态框是否关闭对话框，这里设置为false
            closeOnClickModal: false,
            // 内容渲染器，使用h函数创建elForm组件，并绑定formRef
            contentRenderer: () => h(elForm, { ref: formRef }),
            // 在确认操作之前执行的函数
            beforeSure: (done, { options }) => {
                // 获取表单引用
                const FormRef = formRef.value.getRef();
                // 获取当前表单数据，类型断言为FormItemProps
                const curData = options.props.formInline as FormItemProps;
                // 如果curData.agvids为数组，将curData.agvids转为字符串
                if (Array.isArray(curData.agvids)) {
                    curData.agvids = curData.agvids.join(",");
                }
                if (curData.intervaltime === "") curData.intervaltime = 0;
                // if (title === '编辑') curData.stationList = dialogStatus.stationList;
                curData.stationList = dialogStatus.stationList.map(item => {
                    return {
                        staid: item.staid ?? null,
                        leftlocid: item.leftlocid ?? null,
                        rightlocid: item.rightlocid ?? null,
                    }
                });
                // 将空字符串转换为null
                curData.stationList.forEach(item => {
                    if (!item.staid) message(`请输入对应站点名称`, {
                        type: "error"
                    });
                    return
                });
                // console.log('表单数据=>', curData);
                // 定义一个函数chores，用于执行一些操作
                function chores() {
                    message(`您${title}了路线名称为${curData.name}的这条数据`, {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        // 表单规则校验通过
                        if (title === "新增") {
                            addInspectionroute(curData).then(res => {
                                if (res.Code === 0) {
                                    chores();
                                } 
                            })
                        } else {
                            upDataInspectionroute({ ...curData, id: row.id }).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    // 删除
    function handleDelete(row) {
        ElMessageBox.confirm(
            `是否确认删除名称为${row.name}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            deleteInspectionroute(row.id).then(res => {
                if (res.Code === 0) {
                    message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onMounted(async () => {
        // let { Content: Results } = await inspectionrouteList(form)
        // userSelect.value = Results
        // console.log('Content=>', Results);


        onSearch()
    })

    return {
        columns,
        loading,
        dataList,
        openDialog,
        handleDelete,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange
    }
}